﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class AddUserHandler : IRequestHandler<AddUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> usersRepo;
        private readonly IMapper mapper;

        public AddUserHandler(IBaseRepository<UserModel> usersRepo, IMapper mapper)
        {
            this.usersRepo = usersRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var user = usersRepo.GetAll().Where(x => x.UserName == request.UserName).FirstOrDefault();
            if (user != null)
            {
                res.Msg = "用户名已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var users = mapper.Map<UserModel>(request);
            users.Pwd = "12345678";
            users.CreateName = "张三";
            users.CreateTime = DateTime.Now;

            int i = usersRepo.Add(users);
            if (i > 0)
            {
                res.Msg = "添加成功";
                res.Code = ApiEnum.Success;
                res.Data = i;

            }
            else
            {
                res.Msg = "添加失败";
                res.Code = ApiEnum.Error;
                res.Data = i;

            }
            return Task.FromResult(res);
        }
    }
}
